<?php
/**
 * Created by PhpStorm.
 * User: G
 * Date: 2021/3/27
 * Time: 下午3:25
 */

namespace app\api\command;

use app\admin\model\profit\Config;
use app\admin\model\profit\ProfitDetail;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/*
 * 广告申请 分润 定时任务
 */
class AdsApply extends Command
{

    /**
     * 名称描述配置
     * @author G
     * @date 2021-03-27 下午4:08
     */
    protected function configure()
    {
        $this->setName('ads_apply')->setDescription('Ads Apply Command');
    }

    /**
     * 执行
     * @return int|null|void
     * @author G
     * @date 2021-03-27 下午3:30
     */
    protected function execute(Input $input, Output $output)
    {
        // 业务处理
        $un_share_data = \app\admin\model\profit\AdsApply::where(['is_share' => 0, 'status' => 1])->select();
        if (!$un_share_data) {
            echo '暂无数据';
            return;
        }

        // 获取分润配置 9
        $profit_config_9 = Config::getConfigById(9);

        foreach ($un_share_data as $k => $v) {
            // 分润处理 50%收益 给申请人

            $temp_data = [
                'uid' => $v['uid'],
                'referrer_uid' => $v['uid'],
                're_referrer_uid' => 0,
                'p_uid' => 0,
                'c_uid' => 0,
                'referrer_price' => bcmul($v['price'], $profit_config_9['referrer_price'] / 100, 2),
                're_referrer_price' => 0,
                'p_price' => 0,
                'c_price' => 0,
                't_price' => 0,
                'print' => 9,
                'creat_time' => time(),
                'update_time' => time()
            ];


            $insert_res = ProfitDetail::insert($temp_data);
            if (!$insert_res) {
                throw new Exception('保存分润信息失败');
            }


            // 更新分润状态：已分润
            $update_agent_res = \app\admin\model\profit\AdsApply::where(['id' => $v['id']])->update([
                'is_share' => 1,
                'updatetime' => time(),
            ]);

            if(!$update_agent_res) {
                throw new Exception('更新分润状态失败');
            }

            echo '成功: ' . $v['mobile'] . PHP_EOL;
        }
    }

}